package pine.web.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pine.web.common.grid.Pagination;
import pine.web.dao.UserDao;
import pine.web.model.User;

@Transactional
@Service("UserService")
public class UserServiceImpl implements UserService, UserDetailsService{
	
	private final Logger log = Logger.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDao userDao;
	
	@Override
	public void save(User user) {
		this.userDao.save(user);
	}
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = userDao.loadUserByName(username);
		if (user == null) {
			log.warn("Login Error : user not found...");
			throw new UsernameNotFoundException("Login Error : " + username + " not found!");
		}
		user.getAuthorities();
		return user;
	}
	
	@Override
	public void test() {
		User user = new User();
		user.setUsername("test");
		user.setPassword("admin");
		user.setFullname("t");
		save(user);
		user.setFullname("test");
		save(user);
	}
	
	@Override
	public Pagination<User> findUserByPage() {
		return userDao.findPageByCriteria(null, null);
	}
	
	@Override
	public List<User> listUser() {
		return userDao.loadAll();
	}
}
